﻿using System;
using System.Web;

namespace Codemonk.Updater.Server
{
    public class HttpUpdateServer : IHttpAsyncHandler
    {
        private static Scheduler scheduler = new Scheduler();

        public bool IsReusable { get { return true; } }

        public void ProcessRequest(HttpContext context) { }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var result = new HttpClient { Callback = cb, HttpContext = context };
            scheduler.AddClient(result);
            return result;
        }

        public void EndProcessRequest(IAsyncResult r)
        {
            try
            {
                HttpClient result = r as HttpClient;
                var context = result.HttpContext;
                var stream = result.Stream;
                if (stream == null)
                {
                    context.Response.End();
                    return;
                }
                context.Response.Clear();
                const int size = 1024 * 1024 * 4;//4M
                byte[] buffer = new byte[size];
                using (stream)
                {
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AddHeader("Content-Disposition", "inline;filename=codemonk.");
                    context.Response.BufferOutput = false;
                    var length = stream.Length;
                    while (length > 0 && context.Response.IsClientConnected)
                    {
                        int read = stream.Read(buffer, 0, size);
                        context.Response.OutputStream.Write(buffer, 0, read);
                        context.Response.Flush();
                        length -= read;
                    }
                }
                context.Response.End();
            }
            catch { }
        }
    }
}
